package com.technology.education.utils

import android.text.TextUtils
import android.util.Log
import com.technology.education.BuildConfig
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

/**
 * @author:create by BZY
 * Date: 2019/11/18 15
 */
class LogUtil {
    fun log(msg: String?) {
        if (TextUtils.isEmpty(msg)) {
            return
        }
        if (BuildConfig.DEBUG) {
            Log.i("bzy", msg!!)
        }
    }

    fun printJson(msg: String) {
        if (TextUtils.isEmpty(msg)) {
            return
        }
        val message: String = try {
            when {
                msg.startsWith("{") -> {
                    val jsonObject = JSONObject(msg)
                    jsonObject.toString(4) //最重要的方法，就一行，返回格式化的json字符串，其中的数字4是缩进字符数
                }
                msg.startsWith("[") -> {
                    val jsonArray = JSONArray(msg)
                    jsonArray.toString(4)
                }
                else -> {
                    msg
                }
            }
        } catch (e: JSONException) {
            msg
        }
        log(message)
    }

    companion object {
        @Volatile
        private var toastUtil: LogUtil? = null

        /**
         * 单例
         *
         * @return
         */
        val instance: LogUtil?
            get() {
                if (toastUtil == null) {
                    synchronized(LogUtil::class.java) {
                        if (toastUtil == null) {
                            toastUtil =
                                LogUtil()
                        }
                    }
                }
                return toastUtil
            }
    }
}